﻿#include <thread>
#include <sstream>
#include <QDir>
#include <QLockFile>
#include <QMessageBox>
#include <QApplication>
#include "easylogging++.h"
#include "mainwindow.h"
#include "registerwindow.h"

INITIALIZE_EASYLOGGINGPP

std::string getThreadId(const el::LogMessage*) {
    std::ostringstream oss;
    oss << std::this_thread::get_id();
    return oss.str();
}

int main(int argc, char *argv[])
{
    el::Configurations defaultConf;
    defaultConf.setToDefault();
    
    el::Helpers::installCustomFormatSpecifier(el::CustomFormatSpecifier("%getThreadId", getThreadId));
    // Values are always std::string
    defaultConf.set(el::Level::Info,
        el::ConfigurationType::Format, R"([%datetime][%level][%file:%line][%func][%getThreadId]:%msg)");
    // default logger uses default configurations
    el::Loggers::reconfigureLogger("default", defaultConf);

    QString path = QDir::temp().absoluteFilePath("meterQuery.lock");
    QLockFile lockFile(path);

    bool isLock = lockFile.isLocked();
    // bool QLockFile::tryLock(int timeout = 0)
    // tryLock尝试创建锁定文件。此函数如果获得锁，则返回true; 否则返回false。
    // 如果另一个进程（或另一个线程）已经创建了锁文件，则此函数将最多等待timeout毫秒
    if (!lockFile.tryLock(100))
    {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText("The application is already running.\n"
            "Allowed to run only one instance of the application.");
        msgBox.exec();
        return 1;
    }

    LOG(INFO) << "main start";

    QApplication a(argc, argv);
    RegisterWindow registerWindow;
    MainWindow mainWindow;
    QObject::connect(&registerWindow, SIGNAL(showMain()), &mainWindow, SLOT(receiveLogin()));
    bool succ = registerWindow.init();
    if (!succ) {
        registerWindow.show();
    }
    else {
        mainWindow.show();
    }

    return a.exec();
}
